<!--  -->
<template>
  <div>
    <ul>
      <li v-for="item of msgList" :key="item.id">
        <p>
          <span>{{ item.user }}</span>
          <i>{{ new Date(item.dateTime)}}</i>
        </p>
        <p>
          消息: {{ item.msg }}
        </p>
      </li>
    </ul>

    <input type="text" placeholder="请输入消息" v-model="message" />
    <button @click="handleSendBtnClick">发送</button>
  </div>
</template>

<script>
import { onMounted, reactive, toRefs } from 'vue'
import { useRouter } from 'vue-router';
import { useWebSocket } from '../hooks';

export default {
  name: 'Home',
  setup() {
    const router = useRouter();
    const ws = useWebSocket(handleWsMessage);

    const state = reactive({
      message: '',
      msgList: []
    });

    let username = '';
    onMounted(() => {
      username = localStorage.getItem('username');

      if (!username) {
        router.push('/login');
        return;
      }
    })


    const handleSendBtnClick = () => {
      const _msg = state.message;

      if (!_msg.trim().length) {
        return;
      }

      ws.send(JSON.stringify({
        id: new Date().getTime(),
        user: username,
        dateTime: new Date().getTime(),
        msg: state.message
      }));

      state.message = '';
    }

    function handleWsMessage(e) {
      console.log('websocket message', e);
      const _msgData = JSON.parse(e.data);
      state.msgList.push(_msgData);
      
    }

    return {
      ...toRefs(state),
      handleSendBtnClick,
      handleWsMessage
    }

  }
}
</script>
<style lang='scss' scoped>

</style>